import React, { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import { Form, Input, Button, Checkbox, message } from 'antd';
import md5 from 'md5';
import Api from '../../util/apiUrl';
import './index.css';

const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 16,
  },
};

const Login = (props) => {
  const onFinish = (values) => {
    console.log('Success:', values);
    // 是否保存信息
    if (values.remember) {
      window.localStorage.setItem('loginInfo', JSON.stringify(values));
    } else {
      window.localStorage.setItem('loginInfo', '{}');
    }
    // 登陆操作
    values.password = md5(values.password);
    console.log('加密后', values);
    Api.login(values)
      .then((res) => {
        console.log('登陆返回', res.data);
        if (res.data.isLogin) {
          message.success('登陆成功');
          window.localStorage.setItem('account', res.data.account)
          window.localStorage.setItem('openId', res.data.openId)
          props.history.push('/admin/personalInfo/');
        } else {
          message.error('登陆失败: ' + res.data.msg);
        }
      })
      .catch((err) => {
        console.log('登陆错误', err);
        message.error('登陆失败: ' + err);
      });
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div className="login">
      <div className="center">
        <h1>login</h1>
        <Form
          {...layout}
          name="basic"
          initialValues={JSON.parse(window.localStorage.getItem('loginInfo'))}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="账号"
            name="account"
            rules={[
              {
                required: true,
                message: '请输入账号!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item {...tailLayout} name="remember" valuePropName="checked">
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              登陆
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default withRouter(Login);
